﻿using System;
using System.Diagnostics;

using Microsoft.Practices.ServiceLocation;

using Fuse8.DomainFramework.Configuration;
using Fuse8.DomainFramework.Common.Logging;

namespace Fuse8.DomainFramework.Common.Locator
{
    /// <summary>
    /// 
    /// </summary>
    public static class DependencyServiceLocator
    {
        private static IServiceLocatorEx current;

        /// <summary>
        /// The current ambient container.
        /// </summary>
        public static IServiceLocatorEx Current
        {
            get 
            {
                return current ?? (current = ServiceLocatorEx.CurrentEx); 
            }
        }

        /// <summary>
        /// Set the delegate that is used to retrieve the current container.
        /// </summary>
        /// <param name="newProvider">Delegate that, when called, will return
        /// the current ambient container.</param>
        public static void SetLocatorProvider(ServiceLocatorProviderEx newProvider)
        {
            Guard.ArgumentNotNull(newProvider, "newProvider");

            if (DebugConfiguration.DfTraceSwitch.TraceInfo)
            {   
                TraceListenerEx.WriteLine(
                        string.Format("{0} method used as locator provider", newProvider.Method),
                        "DependencyServiceLocator - SetLocatorProvider");
            }

            ServiceLocatorEx.SetLocatorProvider(newProvider);
            current = null;
        }

        /// <summary>
        /// Set the delegate that is used to retrieve the current container.
        /// </summary>
        /// <param name="newProvider">Delegate that, when called, will return
        /// the current ambient container + lazy init support</param>
        public static void SetLocatorProvider(ServiceLocatorProviderWithLazy newProvider)
        {   
            SetLocatorProvider(new ServiceLocatorProviderEx(newProvider));
        }
    }
}
